package cn.terenas.tool.excel.util;

import cn.terenas.tool.excel.common.constant.Constant;
import lombok.NoArgsConstructor;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFCellStyle;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;

@NoArgsConstructor
public final class CellUtil {

    public static XSSFCell initCellValue(XSSFSheet sheet, int rowNum, int columnNum, String value) {
        XSSFCell cell = createCell(sheet, rowNum, columnNum);
        cell.setCellValue(value);
        return cell;
    }

    public static XSSFCell initCellValue(XSSFSheet sheet, int rowNum, int columnNum, Double value) {
        XSSFCell cell = createCell(sheet, rowNum, columnNum);
        cell.setCellValue(value);
        return cell;
    }

    public static XSSFCell createCell(XSSFSheet sheet, int rowNum, int columnNum) {
        if (sheet != null) {
            XSSFRow row = sheet.getRow(rowNum);
            if (row == null) {
                row = sheet.createRow(rowNum);
                row.setHeight(Constant.DEFAULT_ROW_HEIGHT);
            }
            return row.createCell(columnNum);
        } else {
            throw new RuntimeException("表格数据写入错误!");
        }
    }

    public static void mergeRegion(XSSFSheet sheet, int firstRow, int lastRow, int firstCol, int lastCol) {
        sheet.addMergedRegion(new CellRangeAddress(firstRow, lastRow, firstCol, lastCol));
        XSSFCell firstCell = sheet.getRow(firstRow).getCell(firstCol);
        String stringValue = firstCell.getStringCellValue();
        XSSFCellStyle cellStyle = firstCell.getCellStyle();
        for (int rowNum = firstRow; rowNum < lastRow + 1; rowNum++) {
            for (int colNum = firstCol; colNum < lastCol + 1; colNum++) {
                CellUtil.initCellValue(sheet, rowNum, colNum, stringValue).setCellStyle(cellStyle);
            }

        }
    }
}
